<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input v-model="listQuery.buildingname" placeholder="请输入名称" style="width:300px;height:14px;padding-top:10px;padding-bottom:10px;margin-left:10px;margin-bottom:10px;"/>
      <!--<el-input v-model="listQuery.keyword" style="width: 200px;" class="filter-item" placeholder="请输入菜单名称" @keyup.enter.native="handleFilter"/>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>
    <!--<el-button @click="changeRoute">123</el-button>-->
    <!--<tree-table :data="list" :async="false" :columns="columns" :expand-all="expandAll" border>-->
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column width="80" align="center" label="图像">
        <template slot-scope="scope">
          <img :src="scope.row.buildimageurl" mode="widthFix" style="width: 100%;height: auto;">
        </template>
      </el-table-column>
      <el-table-column width="80" align="center" label="编码">
        <template slot-scope="scope">
          <span>{{ scope.row.buldingid }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="建筑名称">
        <template slot-scope="scope">
          <span>{{ scope.row.buildingname }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="监管单位">
        <template slot-scope="scope">
          <span v-for="option in supervisorOptions" :key="option">
            <p v-if="option.value===scope.row.supervisor">{{ option.label }}</p>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="地理位置">
        <template slot-scope="scope">
          <span v-if="scope.row.longitude!==undefined && scope.row.longitude!==''">
            <p>{{ '经度:'+scope.row.longitude }}</p>
          </span>
          <span v-if="scope.row.latitude!==undefined && scope.row.latitude!==''">
            <p>{{ '纬度:'+scope.row.latitude }}</p>
          </span>
          <span v-if="scope.row.levation!==undefined && scope.row.levation!==''">
            <p>{{ '高度:'+scope.row.levation }}</p>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="详细地址">
        <template slot-scope="scope">
          <!--<span v-if="scope.row.province!==null && scope.row.province!==''">{{ scope.row.province+' ' }}</span>-->
          <!--<span v-if="scope.row.city!==null && scope.row.city!==''">{{ scope.row.city+' ' }}</span>-->
          <!--<span v-if="scope.row.zone!==null && scope.row.zone!==''">{{ scope.row.zone+' ' }}</span>-->
          <!--<span v-if="scope.row.district!==null && scope.row.district!==''">{{ scope.row.district+' ' }}</span>-->
          <!--<span v-if="scope.row.address!==null && scope.row.address!==''">{{ scope.row.address }}</span>-->
          <span>{{ scope.row.intactaddress }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.limit"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>

    <!-- 增加页 -->
    <div v-if="dialogFormVisible">
      <el-dialog :title="textMap[dialogStatus]" :fullscreen="false" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 450px; margin-left:50px;">
          <el-form-item label="建筑名称" prop="buildingname">
            <el-input v-model="temp.buildingname"/>
          </el-form-item>
          <el-form-item v-if="dialogStatus==='update'" label="监管单位" prop="supervisor">
            <el-select v-model="temp.supervisor" :disabled="false" class="filter-item select-width-100" placeholder="请选择">
              <el-option v-for="item in supervisorOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <!--<el-form-item label="地理位置编码id" prop="zoneid">-->
          <!--<el-input v-model="temp.zoneid"/>-->
          <!--</el-form-item>-->

          <el-form-item label="省市区" prop="province">
            <el-select v-model="temp.province" class="filter-item select-width-30" placeholder="省级地区" prop="province" @change="chooseProvince()">
              <el-option v-for="item in provinceOpt" :key="item.value+''" :label="item.label" :value="item.value+''"/>
            </el-select>
            <el-select v-model="temp.city" class="filter-item select-width-30" placeholder="市级地区" prop="city" @change="chooseCity()">
              <el-option v-for="item in cityOpt" :key="item.value+''" :label="item.label" :value="item.value+''"/>
            </el-select>
            <el-select v-model="temp.zone" class="filter-item select-width-30" placeholder="区级地区" prop="zone">
              <el-option v-for="item in zoneOpt" :key="item.value+''" :label="item.label" :value="item.value+''"/>
            </el-select>
          </el-form-item>

          <el-form-item label="所在街道" prop="district">
            <el-input v-model="temp.district"/>
          </el-form-item>
          <!--<el-form-item label="经度" prop="longitude">-->
          <!--<el-input v-model="temp.longitude"/>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="纬度" prop="latitude">-->
          <!--<el-input v-model="temp.latitude"/>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="高度" prop="levation">-->
          <!--<el-input v-model="temp.levation"/>-->
          <!--</el-form-item>-->
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="temp.address"/>
          </el-form-item>
          <el-form-item label="图像信息" prop="buildimageurl">
            <el-input v-model="temp.buildimageurl" class="imageinput"/>
            <el-button size="medium" type="primary" class="uploadbutton" @click="activeTrigger">点击上传</el-button>
            <el-upload
              ref="uploadTool"
              :limit="1"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :http-request="getUploadAddress"
              class="upload-demo"
              action=""
              list-type="picture">
              <button id="trigger" style="display: none"/>
            </el-upload>
          </el-form-item>
          <el-form-item label="经纬度" prop="longitude">
            <div id="lola">
              <el-input v-model="temp.longitude"/>
              <el-input v-model="temp.latitude"/>
              <el-button type="primary" size="medium" @click="openMap">定位</el-button>
            </div>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
          <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
        </div>
      </el-dialog>
    </div>

    <!--百度地图 外面加一层div是为了关闭el-dialog 再打开时可以重新加载el-dialog -->
    <div v-if="mapVisible">
      <el-dialog :visible.sync="mapVisible" title="定位" width="60%" @close="closeMap">
        <baidu-map
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          :ak="ak"
          class="map">
          <bm-marker ref="marker" :position="{lng: center.lng, lat: center.lat}" :dragging="true" @dragend="dragEndPosition"/>
          <bm-city-list ref="bmcity" anchor="BMAP_ANCHOR_TOP_LEFT" @changeAfter="changeMarker"/>
        </baidu-map>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeMap">{{ $t('table.cancel') }}</el-button>
          <el-button type="primary" @click="confirmSite">{{ $t('table.confirm') }}</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { addBuilding, deleteBuilding, fetchBuildingList, updateBuilding } from '@/api/fire/building/base'
import { selectLabelValue } from '@/api/fire/supervisor/base'
import { getProvinceOpt, getCityOrZoneOpt } from '@/api/fire/supervisor/danger'
import { getAk } from '@/api/fire/map/map'
import { BaiduMap, BmMarker, BmCityList } from 'vue-baidu-map'
import { uploadPic } from '@/api/fire/proprietor/monitor'
import waves from '@/directive/waves' // 水波纹指令
export default {
  name: 'BuildingComponent',
  directives: {
    waves
  },
  components: {
    // 指定组件模板
    BaiduMap,
    BmMarker,
    BmCityList
  },
  data() {
    return {
      expandAll: false,
      tableKey: 0,
      assetTableKey: 0,
      myAssetTableKey: 0,
      list: null,
      assetList: null,
      myAssetList: null,
      total: null,
      listLoading: true,
      treeSelectedOptions: [],
      supervisorOptions: [],
      provinceOpt: [],
      cityOpt: [],
      zoneOpt: [],
      listQuery: {
        page: 1,
        limit: 10,
        buildingname: '',
        owner: ''
      },
      // sexOptions: getDictList('sex'),
      showReviewer: false,
      temp: {
        buldingid: undefined,
        createtime: '',
        buildingname: '',
        supervisor: '',
        updatetime: '',
        longitude: '',
        latitude: '',
        levation: '0',
        province: '',
        city: '',
        zone: '',
        district: '',
        address: '',
        zoneid: '',
        buildimageurl: ''
      },
      dialogFormVisible: false,
      dialogAssetFormVisible: false,
      dialogDeviceFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改建筑物',
        create: '添加建筑物'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        buildingname: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 10, min: 4, message: '长度必须大于4小于10', trigger: 'blur' }
        ],
        // supervisor: [{ required: true, message: '请选择监管单位', trigger: 'blur' }],
        // longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        // latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
        // levation: [{ required: true, message: '请输入高度', trigger: 'blur' }],
        province: [{ required: true, message: '请输入省', trigger: 'blur' }],
        city: [{ required: true, message: '请输入市', trigger: 'blur' }],
        zone: [{ required: true, message: '请输入区', trigger: 'blur' }],
        district: [{ required: true, message: '请输入描述', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
        // zoneid: [{ required: true, message: '请输入位置id', trigger: 'blur' }]
      },
      downloadLoading: false,
      permissionTreeList: null,
      permissionQuery: {
        sort: '+id'
      },
      buttonInit: [
        {
          title: '查询',
          permission: 'list'
        },
        {
          title: '添加',
          permission: 'add'
        },
        {
          title: '更新',
          permission: 'update'
        },
        {
          title: '删除',
          permission: 'delete'
        },
        {
          title: '导出',
          permission: 'export'
        },
        {
          title: '导入',
          permission: 'import'
        }
      ],
      btn_query: false,
      btn_add: false,
      btn_edit: false,
      btn_delete: false,
      address: '',
      mapVisible: false,
      ak: '',
      // 经纬度
      center: { lng: 0, lat: 0 },
      // 地图展示级别
      zoom: 12,
      // 拖拽marker后的lng
      de_lng: 0,
      // 拖拽marker后lat
      de_lat: 0,
      // 文件上传↓↓
      fileList: [],
      file: null
    }
  }, watch: {
    'location': {
      handler() {
        this.drawLocation()
      },
      deep: true
    },
    visible() {
      console.log('ddd')
    }
  },
  created() {
    this.getList()
    this.btn_query = this.checkPermission(['supervisor:base:list'])
    this.btn_add = this.checkPermission(['supervisor:base:add'])
    this.btn_edit = this.checkPermission(['supervisor:base:update'])
    this.btn_delete = this.checkPermission(['supervisor:base:delete'])
    // this.changeRoute()
    this.querySupervisorOptions()
    this.queryProvinceOpt()
    // 向后台获取百度ak
    getAk().then(response => {
      this.ak = response.data.context
    })
  },
  methods: {
    changeRoute() {
      this.$store.dispatch('ChangeRoute')
      this.$store.commit('BACK_VISIBLE', true)
    },
    getList() {
      this.listLoading = true
      fetchBuildingList(this.listQuery).then(response => {
        this.list = response.data.context.records
        this.total = response.data.context.total
        this.listLoading = false
      })
    },
    changeRequireAuth() {

    },
    handleFilter() {
      this.getList()
    },
    resetTemp() {
      this.temp = {
        buldingid: undefined,
        createtime: '',
        buildingname: '',
        supervisor: '',
        updatetime: '',
        longitude: '',
        latitude: '',
        levation: '0',
        province: '',
        city: '',
        zone: '',
        district: '',
        address: '',
        zoneid: '',
        buildimageurl: ''
      }
      this.treeSelectedOptions.length = 0
    },
    handleCreate() {
      this.resetTemp()
      this.changeRequireAuth()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // 清除上传列表数据
      this.$refs.uploadTool.clearFiles()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // 预处理提交的数据
      // const parentIds = this.temp.parentIds
      // if (parentIds !== undefined && parentIds !== '') {
      //   if (parentIds instanceof Array && parentIds.length > 0) {
      //     const parentId = parentIds[parentIds.length - 1]
      //     this.temp.parentId = parentId
      //   }
      // }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // if (this.temp.parentIds !== undefined && this.temp.parentIds !== '') {
          //   this.temp.parentIds.length = 0
          // }
          addBuilding(this.temp).then((response) => {
            const data = response.data
            if (data.status === '0') {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: data.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetTemp()
      this.temp = Object.assign({}, row) // copy obj=
      this.changeRequireAuth()
      // 加载省市区字典
      this.chooseProvince(false)
      this.chooseCity(false)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // 清除上传列表数据
      this.$refs.uploadTool.clearFiles()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // const parentIds = this.temp.parentIds
          // if (parentIds !== undefined && parentIds !== '') {
          //   if (parentIds instanceof Array && parentIds.length > 0) {
          //     const parentId = parentIds[parentIds.length - 1]
          //     this.temp.parentId = parentId
          //   }
          // }
          // if (this.temp.parentIds !== undefined && this.temp.parentIds !== '') {
          //   this.temp.parentIds = undefined
          // }
          // if (this.temp.parent !== undefined) {
          //   this.temp.parent = undefined
          // }
          const tempData = Object.assign({}, this.temp)
          updateBuilding(tempData).then((response) => {
            const data = response.data
            if (data.status === '0') {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: data.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认要删除建筑物么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBuilding(row.buldingid).then(response => {
          const data = response.data
          if (data.status === '0') {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          } else {
            this.$notify({
              title: '失败',
              message: data.message,
              type: 'error',
              duration: 2000
            })
          }
        })
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleAssetManage(row) {
      this.$router.push({ path: 'asset/index' })
    },
    handleDeviceManage(row) {
      console.log('submit!')
      this.$router.push('/device')
    },
    querySupervisorOptions() {
      selectLabelValue().then(response => {
        if (response.data.status === '0') {
          this.supervisorOptions = response.data.context
        }
      })
    },
    queryProvinceOpt() {
      getProvinceOpt().then(response => {
        this.provinceOpt = response.data.context
      })
    },
    chooseProvince(isClean) {
      console.log(isClean)
      getCityOrZoneOpt(this.temp.province).then(response => {
        this.cityOpt = response.data.context
      })
      if (isClean === undefined || isClean) {
        this.zoneOpt = []
        this.temp.city = ''
        this.temp.zone = ''
      }
    },
    chooseCity(isClean) {
      console.log(isClean)
      getCityOrZoneOpt(this.temp.city).then(response => {
        this.zoneOpt = response.data.context
      })
      if (isClean === undefined || isClean) {
        this.temp.zone = ''
      }
    },
    // 地图↓↓
    openMap() {
      this.resetMap()
      this.zoom = 5
      if (this.dialogStatus === 'update') {
        // 打开时回显
        if (this.temp.longitude !== '' && this.temp.longitude !== undefined &&
          this.temp.latitude !== '' && this.temp.latitude !== undefined) {
          this.center.lng = this.temp.longitude
          this.center.lat = this.temp.latitude
          this.de_lng = this.temp.longitude
          this.de_lat = this.temp.latitude
          this.zoom = 12
        }
      }
      this.mapVisible = true
    },
    closeMap() {
      this.mapVisible = false
    },
    confirmSite() {
      // 确认时将marker中的lng,lat的值赋给temp里的longitude，latitude
      this.temp.longitude = this.de_lng
      this.temp.latitude = this.de_lat
      this.mapVisible = false
    },
    resetMap() {
      this.center.lng = 116.405419
      this.center.lat = 39.914271
      this.de_lng = 116.405419
      this.de_lat = 39.914271
    },
    changeMarker() {
      // 选择城市以后将marker转移
      this.center.lng = this.$refs.bmcity.map.Oe.lng
      this.center.lat = this.$refs.bmcity.map.Oe.lat
      this.de_lng = this.$refs.bmcity.map.Oe.lng
      this.de_lat = this.$refs.bmcity.map.Oe.lat
      this.zoom = 12
    },
    dragEndPosition(e) {
      // 拖拽后的marker所在坐标
      this.de_lng = e.point.lng
      this.de_lat = e.point.lat
    },
    // 地图↑↑
    // 文件上传↓↓
    getUploadAddress(param) {
      const formData = new FormData()
      formData.append('file', param.file, param.file.name)
      uploadPic(formData).then(response => {
        this.temp.buildimageurl = response.data.context
      })
    },
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      this.temp.buildimageurl = ''
    },
    activeTrigger() {
      document.getElementById('trigger').click()
    }
    // 文件上传↑↑

  }
}
</script>
<style>
  .select-width-30{
    width: 32%;
  }
  .select-width-100{
    width: 100%;
  }
  #lola div{
    width: 38%;
    display: inline-block;
  }
  .imageinput{
    width: 73%;
    display: inline-block;
  }
  .uploadbutton{
    width: 25%;
    display: inline-block;
    padding: 10px 0px;
  }
  .el-upload{
    display: none;
  }
  /*必须给容器指高度，要不然地图将显示在一个高度为0的容器中，自然看不到*/
  .map {
    width: 100%;
    height: 500px;
  }
  .anchorBL {
    display: none;
  }
</style>
